import React from 'react';
import _isEqual from 'lodash/isEqual';

export function delay(ms) {
    return new Promise((resolve, reject) => {
        try {
            setTimeout(() => {
                resolve();
            }, ms);
        } catch (err) {
            reject(err);
        }
    });
}

export function injectChildren(children, properties) {
    return React.Children.map(children, child => {
        if (child) {
            const { type: childType } = child;
            if (typeof childType === 'string') {
                return child;
            }
            return React.cloneElement(child, {
                ...properties
            });
        }
        return child;
    });
}

export function transferMenuData(menuLoading, menuData) {
    if (menuLoading) {
        return null;
    }
    return menuData;
}

export function withRoutePage(WrappedComponent) {
    return class extends React.Component {
        shouldComponentUpdate(nextProps) {
            const {
                children: nextChildren,
                computedMatch: nextComputedMatch,
                history: nextHistory,
                location: nextLocation,
                match: nextMatch,
                route: nextRoute,
                staticContext: nextStaticContext,
                ...nextRest
            } = nextProps;
            const {
                children: thisChildren,
                computedMatch: thisComputedMatch,
                history: thisHistory,
                location: thisLocation,
                match: thisMatch,
                route: thisRoute,
                staticContext: thisStaticContext,
                ...thisRest
            } = this.props;
            // 注入数据变化，刷新组件
            if (!_isEqual(nextRest, thisRest)) {
                console.log('update by 数据变化');
                return true;
            }

            const { pathname: nextPathname, search: nextSearch, state: nextState } = nextLocation;
            const { pathname: thisPathname, search: thisSearch, state: thisState } = thisLocation;
            const isLocationChange =
                nextPathname !== thisPathname ||
                nextSearch.replace('?', '') !== thisSearch.replace('?', '') ||
                !_isEqual(nextState, thisState);
            // 路由变化，刷新组件
            if (isLocationChange) {
                console.log('update by 路由变化');
                return true;
            }
            return false;
        }

        render() {
            return <WrappedComponent {...this.props} />;
        }
    };
}
